package com.caineng.zhaobiao.zbapi.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.caineng.zhaobiao.zbapi.utils.redis.CainengRedisUtils;

import java.util.concurrent.TimeUnit;

//阿里云

/**
 * 短信缓存已经改成了redis
 * 2022年4月2日
 */
public class SmsSampleUtils {


/*  LTAI5t9yasQA6jpFW51CtStQ
nBW3IQiDIObzNvZHVLnkJMu8815wR0
    */

    //lifenyao账号2024年12月4日创建  https://ram.console.aliyun.com/manage/ak?spm=a2c8b.20231166.top-nav.dak.2a4f336a6OU3or
    private static final String accessKeyId = "LTAI5t9yasQA6jpFW51CtStQ";
    private static final String accessKeySecret = "nBW3IQiDIObzNvZHVLnkJMu8815wR0";

    private static final String signName = "朋利科技";
    //private static final String templateCode = "SMS_221640862";//注册短信模板



    //2024年12月30日 申请阿里云短信
    private static final String templateCode = "SMS_476765612";//
    //短信发送客户端
    private static Client acsClient;

    static {

        try {
            acsClient = createClient(accessKeyId, accessKeySecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
    public static AjaxResult sendSms(String phone) {


        if(!StringUtils.isTruePhone(phone)){
            return AjaxResult.error("手机号码不正确");
        }

        //使用redis缓存
        CainengRedisUtils redisUtils = SpringUtil.getBean(CainengRedisUtils.class);

        //一分钟一个手机号码限制只能发送一次
        String data = redisUtils.getCacheObject("SMS_ONE_MINUTE_"+phone);
        if(StrUtil.isNotEmpty(data)){
            return AjaxResult.error("请勿频繁发送短信!");
        }

        //TODO 一天一个手机号码最多只能接收5次验证码
        String key = "SMS_PHONE:"+phone+"_"+ DateUtil.today();
        Integer num =  redisUtils.getCacheObject(key) ;
        if(num==null){
            num=1;
        }else{
            num++;
        }
        if(num>5){
            return AjaxResult.error("今天"+phone+"接收的短信已经超过限制，请明天再试");
        }
        //设置的时间为今天晚上23:59:59到期
        redisUtils.setCacheObject(key,num, StringUtils.timesCountDay()*1000, TimeUnit.MILLISECONDS);


        try {
            SendSmsRequest request = new SendSmsRequest();
            String code = getCode();
            request.setPhoneNumbers(phone);
            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse sendSmsResponse = acsClient.sendSms(request);
            System.out.println("发送短信."+ JSONUtil.toJsonStr(sendSmsResponse));
            if (sendSmsResponse.getBody().getCode().equals("OK")) {

                //一分钟一个手机号码只能发送一次短信
                redisUtils.setCacheObject("SMS_ONE_MINUTE_"+phone,code,1*60*1000L,TimeUnit.MILLISECONDS);

                //短信验证码5分钟之内有效
                redisUtils.setCacheObject("SMS_"+phone, code,5*60*1000L,TimeUnit.MILLISECONDS);
                return AjaxResult.success("发送成功");
            } else {
                return AjaxResult.error("发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("发送失败");
        }
    }

    /**
     * 获取验证码
     * @return
     */
    private static String getCode() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            sb.append((int) Math.floor(Math.random() * 10));
        }
        return sb.toString();
    }

    /**
     * 检查验证码
     * @param phone
     * @param code
     * @return
     */
    public static AjaxResult checkCode(String phone, String code) {
        //使用redis缓存
        CainengRedisUtils redisUtils = SpringUtil.getBean(CainengRedisUtils.class);
        String key = "SMS_"+phone;
        String data = redisUtils.getCacheObject(key);
        if (data == null) {
            return AjaxResult.error("验证码已过期,请重新获取");
        }

        if (!data.equals(code)) {
            return AjaxResult.error("验证码错误");
        }
        redisUtils.deleteObject(key);
        return AjaxResult.success("正确");
    }

    public static void main(String[] args) {
        sendSms("13357225692");
    }

}
